import nickname as nickname
from Tools.scripts.make_ctype import method
from flask import Blueprint, render_template, request, jsonify, session, make_response, redirect, g

from application import db, app
from common.libs.DateHelper import getCurrentTime
from common.libs.Helper import ops_renderErrJSON, ops_renderJSON, ops_render
from common.libs.UrlManager import UrlManager
from common.libs.UserService import UserService
from common.models.user import User
from common.models.user_info import UserInfo

member_page = Blueprint("member_page", __name__)


@member_page.route('/reg', methods=['GET', 'POST'])
def reg():
    if request.method == "GET":
        return render_template('member/reg.html')
    req = request.values
    login_name = req['login_name'] if "login_name" in req else ""
    login_pwd1 = req['login_pwd1'] if "login_pwd1" in req else ""
    login_pwd2 = req['login_pwd2'] if "login_pwd2" in req else ""
    nick_name = req['nick_name'] if "nick_name" in req else ""
    if login_name is None or len(login_name) < 1:
        return ops_renderErrJSON(msg="用户名错误")
    if login_pwd1 is None or len(login_pwd1) < 5:
        return ops_renderErrJSON(msg="请确认密码是否正确，密码长度不小于5")
    if login_pwd2 is None or login_pwd2 != login_pwd1:
        return ops_renderErrJSON(msg="确认密码与密码不一致")
    if nick_name is None or len(nick_name) < 1:
        return ops_renderErrJSON(msg="nick_name is null")
    user_info = User.query.filter_by(login_name=login_name).first()
    if user_info:
        return ops_renderErrJSON(msg="用户名已被注册")

    user = User()
    user.login_name = login_name
    # model_user.nickname = nick_name
    user.login_salt = UserService.geneSalt(10)
    user.login_pwd = UserService.genePwd(login_pwd1, user.login_salt)
    db.session.add(user)
    db.session.commit()
    info = User.query.filter_by(login_name=login_name).first()

    model_user = UserInfo()
    model_user.nickname = nick_name
    model_user.created_time = model_user.updated_time = getCurrentTime()
    model_user.login_id = info.id
    db.session.add(model_user)
    db.session.commit()

    return ops_renderJSON(msg="注册成功")


@member_page.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("member/login.html")
    req = request.values
    login_name = req['login_name'] if "login_name" in req else ""
    login_pwd = req['login_pwd'] if "login_pwd" in req else ""
    if login_name is None or len(login_name) < 1:
        return ops_renderErrJSON(msg="用户名错误,请输入正确的用户名")
    if login_pwd is None or len(login_pwd) < 5:
        return ops_renderErrJSON(msg="用户密码错误，请输入正确的用户密码")
    user_info = User.query.filter_by(login_name=login_name).first()
    if user_info is None:
        return ops_renderErrJSON(msg="请输入正确的用户名和密码 -1 ~~~")
    if user_info.login_pwd != UserService.genePwd(login_pwd, user_info.login_salt):
        return ops_renderErrJSON(msg="请输入正确的用户名和密码 -2 ~~~")
    if user_info.status != 1:
        return ops_renderErrJSON(msg="用户状态已失效，请联系管理员重新激活~~~")

    # session['uid'] = user_info.id
    response = make_response(ops_renderJSON(msg="登陆成功"))
    # print(app.config['AUTH_COOKIE_NAME'], UserService.geneAuthCode(user_info))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'],
                        "%s#%s" % (UserService.geneAuthCode(user_info), user_info.id), 60 * 60 * 24 * 120)
    # app.logger.info("cookie")
    return response


@member_page.route('/logout')
def logout():
    response = make_response(redirect(UrlManager.buildUrl("/")))
    response.delete_cookie(app.config["AUTH_COOKIE_NAME"])
    return response


@member_page.route('/update', methods=['GET', 'POST'])
def update():
    # info =
    if request.method == 'GET':
        return ops_render("/member/update.html", {'nickname_old': g.current_user.nickname})
    req = request.values
    new_nickname = req['new_nickname'] if 'new_nickname' in req else None
    if not new_nickname:
        return ops_renderErrJSON(msg="新昵称不能为空~~")
    login_id = g.current_user.login_id
    info = UserInfo.query.filter_by(login_id=login_id).first()
    if not info:
        return ops_renderErrJSON(msg="用户不存在？")
    info.nickname = new_nickname
    info.updated_time = getCurrentTime()
    db.session.add(info)
    db.session.commit()
    g.current_user = info
    return ops_renderJSON(msg="修改成功")
